package com.bnz.manager.service.impl;

import com.bnz.manager.dao.SpecificationOptionDao;
import com.bnz.manager.entity.SpecificationOptionEntity;
import com.bnz.manager.entity.group.Specification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bnz.common.utils.PageUtils;
import com.bnz.common.utils.Query;

import com.bnz.manager.dao.SpecificationDao;
import com.bnz.manager.entity.SpecificationEntity;
import com.bnz.manager.service.SpecificationService;


@Service("specificationService")
public class SpecificationServiceImpl extends ServiceImpl<SpecificationDao, SpecificationEntity> implements SpecificationService {

    @Autowired
    private SpecificationOptionDao specificationOptionDao;
    @Autowired
    private SpecificationDao specificationDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpecificationEntity> page = this.page(
                new Query<SpecificationEntity>().getPage(params),
                new QueryWrapper<SpecificationEntity>()
        );

        return new PageUtils(page);
    }

    //保存规格选项
    @Override
    public void save(Specification specification) {
        //添加规格
        SpecificationEntity entity = new SpecificationEntity();
        entity.setSpecName(specification.getSpecName());
        specificationDao.insert(entity);

        //添加规格选项 ----先遍历
        for (SpecificationOptionEntity option : specification.getOptions()) {
            //绑定规格id的值
            option.setSpecId(entity.getId());
            //添加规格选项
            specificationOptionDao.insert(option);
        }
    }

    //修改规格及规格选项    ---处理一对多和多对多的关系,处理手法先删掉规格选项列表
    @Override
    public void update(Specification specification) {
        //1.先删点规格id和对应的选项列表
        specificationOptionDao.delete(new QueryWrapper<SpecificationOptionEntity>().eq("spec_id",specification.getId()));
        //修改规格对象
        SpecificationEntity entity = new SpecificationEntity(specification.getId(),specification.getSpecName());
        specificationDao.updateById(entity);
        //添加规格选项
        for (SpecificationOptionEntity option : specification.getOptions()) {
            //将规格选项上的spec_id与规格对象的id进行绑定
            option.setSpecId(specification.getId());
            //添加规格选项
            specificationOptionDao.insert(option);
        }
    }

//    删除规格规格选项
    @Override
    public void delete(List<String> ids) {
        //删除规格.
        specificationOptionDao.delete(new QueryWrapper<SpecificationOptionEntity>().in("spec_id",ids));
        //根据规格id来删除规格选项
        specificationDao.deleteBatchIds(ids);

    }

}